#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
分析sticklistmain项目的实际依赖项，帮助进一步优化PyInstaller打包大小
"""

import sys
import os
import pkgutil
import importlib
from pathlib import Path

# 添加项目路径
sys.path.insert(0, r"H:\MY\python\wpython")
sys.path.insert(0, r"H:\MY\python\wpython\.venv\Lib\site-packages")

def analyze_imports(file_path):
    """分析Python文件中的导入语句"""
    imports = set()
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            
        # 简单的导入语句识别
        lines = content.split('\n')
        for line in lines:
            line = line.strip()
            if line.startswith('import ') or line.startswith('from '):
                # 提取模块名
                if line.startswith('import '):
                    module = line.split()[1].split('.')[0]
                    imports.add(module)
                elif line.startswith('from ') and 'import' in line:
                    module = line.split()[1].split('.')[0]
                    imports.add(module)
    except Exception as e:
        print(f"分析文件 {file_path} 时出错: {e}")
    
    return imports

def get_project_imports():
    """获取项目中实际使用的模块"""
    project_path = Path(r"H:\MY\python\wpython\top\wardyan\projects\checktool\autokill")
    all_imports = set()
    
    # 分析主要文件
    main_files = [
        project_path / "sticklistmain.py",
        project_path / "sticklistwindow.py",
        project_path / "sticklist.py"
    ]
    
    for file_path in main_files:
        if file_path.exists():
            imports = analyze_imports(file_path)
            all_imports.update(imports)
            print(f"{file_path.name} 中的导入: {', '.join(imports)}")
    
    return all_imports

def check_module_size(module_name):
    """检查模块是否是大型模块"""
    large_modules = {
        'numpy', 'pandas', 'matplotlib', 'scipy', 'sklearn', 'tensorflow', 'torch', 'PIL',
        'cv2', 'pyqt5', 'kivy', 'pygame', 'flask', 'django', 'requests', 'bs4'
    }
    
    return module_name.lower() in large_modules

def main():
    print("=== 项目依赖分析 ===")
    print()
    
    # 获取项目导入
    project_imports = get_project_imports()
    print()
    print("项目中检测到的导入模块:")
    for imp in sorted(project_imports):
        size_indicator = " [LARGE]" if check_module_size(imp) else ""
        print(f"  {imp}{size_indicator}")
    
    print()
    print("=== 建议的PyInstaller优化策略 ===")
    print("1. 在spec文件的hiddenimports中只包含以上检测到的模块")
    print("2. 在excludes中添加未列出但可能被自动包含的大型模块")
    print("3. 确保只导入PySide6中实际使用的子模块")
    print()
    
    # 检查当前环境中安装的包
    print("=== 环境中安装的可能相关包 ===")
    installed_packages = [pkg.name for pkg in pkgutil.iter_modules()]
    relevant_packages = [pkg for pkg in installed_packages if any(imp in pkg for imp in project_imports)]
    
    for pkg in sorted(relevant_packages):
        print(f"  {pkg}")

if __name__ == "__main__":
    main()